﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Text;
using Sale_Operation;
using Sale_Common;
using Sale_Model;
using SaleSystem;
using ExtAspNet;


namespace SaleSystem.Business
{
    public partial class frm_MyBackBillEdit : PageBase
    {
        #region Page Event
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {

                tb_SBDeta_PInfo_Id.OnClientTriggerClick = win_Content2.GetSaveStateReference(tb_SBDeta_PInfo_Id.ClientID, this.hf_SBDeta_PInfo_Id.ClientID, this.nb_SBDeta_Count.ClientID, this.nb_SBDeta_Price.ClientID, this.nb_SBDeta_Money.ClientID, hf_SBDeta_Price.ClientID)
                                        + win_Content2.GetShowReference("~/ComPage/frm_ProductChooseList.aspx?PInfo_Id=");
                //tb_SBDeta_PInfo_Id.OnClientTriggerClick = win_Content.GetSaveStateReference(tb_SBDeta_PInfo_Id.ClientID, this.hf_SBDeta_PInfo_Id.ClientID)
                //         + win_Content.GetShowReference("~/ComPage/frm_ProductChooseList.aspx?PInfo_Id=" + this.tb_SBDeta_PInfo_Id.GetValueReference());

                InitControl();
                GetAndBind();


            }
            else if (Request[LinkService.RefreshTag] == "bnTotal")
            {
                bn_Total_Click(null, null);
            }
        }
        protected void ddl_SBill_PayTypeSelectedChanged(object obj, EventArgs e)
        {
            SysConfig SM = new SysConfig();
            if (this.ddl_MBB_PayType.SelectedValue == "1")//现金
            {
                SM.SConf_Id = 4;
            }
            else
                SM.SConf_Id = 5;
            SysConfigOp op = new SysConfigOp();
            op.GetConfig(SM);
            this.ddl_MBB_AList_Id.SelectedValue = SM.SConf_Value;
        }  
        protected void bnSave_Click(object sender, EventArgs e)
        {
            //如果是修改，保存前先校验下该单据状态是否已经被入库了，如果入库了则不能修改
            if (this.Id != 0)
            {
                SModel.MBB_Id = this.Id;
                Manager.GetModel(SModel);
                if (SModel.MBB_State == 1)
                {
                    ExtAspNet.Alert.Show("该返货单已经结算，不能修改！", "操作提示！", MessageBoxIcon.Warning);
                    return;
                }
            }

            bool blHasExists = Manager.HasExists(SModel);
            if (blHasExists)
            {
                ExtAspNet.Alert.ShowInTop("返货单编码已经存在，请重新输入！", MessageBoxIcon.Information);
            }
            else
            {
                SModel.CreateMan = LinkService.GetCurrentUser().SUser_Id;
                SModel.CreateTime = System.DateTime.Now;
                SModel.State = 1;
                SModel.MBB_AList_Id = ValueHandler.GetIntNumberValue(this.ddl_MBB_AList_Id.SelectedValue);
                SModel.MBB_Code = this.tb_MBB_Code.Text;
                SModel.MBB_Date = DateTime.Parse(this.dp_MBB_Date.Text);
                SModel.MBB_Money = ValueHandler.GetDecNumberValue(this.nb_MBB_Money.Text);
                SModel.MBB_PayType = ValueHandler.GetIntNumberValue(this.ddl_MBB_PayType.SelectedValue);
                SModel.MBB_Output = 0;
                SModel.MBB_State = 0;
                SModel.MBB_Reason = this.tb_MBB_Reason.Text;
                SModel.MBB_SUser_Id = ValueHandler.GetIntNumberValue(this.ddl_MBB_SUser_Id.SelectedValue);
                SModel.MBB_Supp_Id = ValueHandler.GetIntNumberValue(this.ddl_MBB_Supp_Id.SelectedValue);
                bool blRes = Manager.Save(SModel, dtDetail);
                if (blRes)
                    ExtAspNet.PageContext.RegisterStartupScript(ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));

                else
                    ExtAspNet.Alert.ShowInTop("返货单信息编辑失败！", MessageBoxIcon.Error);


          
            }
        }
        /// <summary>
        /// 添加产品明细
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAdd_Click(object sender, EventArgs e)
        {

            if (hf_SBDeta_PInfo_Id.Text.Trim() == "")
            {
                ExtAspNet.Alert.Show("请先选中产品后再做此操作！", "提示！", MessageBoxIcon.Warning);
                return;
            }
            else
            {
                DataTable dt = dtDetail;


                ProductInfoOp ProductManager = new ProductInfoOp();
                ProductInfo SM = new ProductInfo();
                SM.PInfo_Id = ValueHandler.GetIntNumberValue(hf_SBDeta_PInfo_Id.Text);
                //判断单据中是否存在该产品
                DataView dv = new DataView(dt);
                dv.RowFilter = "MBBDeta_PInfo_Id=" + SM.PInfo_Id.ToString() + " AND MBBDeta_Id<>" + SBDeta_Id;
                if (dv.Count > 0)
                {
                    ExtAspNet.Alert.Show("单据中已经存在该产品信息！", "提示！", MessageBoxIcon.Warning);
                    return;
                }
                DataRow dr = null;
                if (this.btnAdd.Text == "添加")
                {
                    dr = dt.NewRow();
                    dt.Rows.Add(dr);

                }
                else
                {
                    DataView dv0 = new DataView(dt);
                    dv0.RowFilter = "MBBDeta_Id=" + SBDeta_Id;
                    if (dv0.Count > 0)
                        dr = dv0[0].Row;
                }
                ProductManager.GetModel(SM);
                dr["PInfo_Code"] = SM.PInfo_Code;
                dr["PInfo_Name"] = SM.PInfo_Name;
                dr["MBBDeta_PInfo_Id"] = this.hf_SBDeta_PInfo_Id.Text;
                dr["MBBDeta_MBB_Id"] = this.Id;
                dr["MBBDeta_Count"] = ValueHandler.GetIntNumberValue(this.nb_SBDeta_Count.Text);
                dr["MBBDeta_Price"] = ValueHandler.GetDecNumberValue(this.nb_SBDeta_Price.Text);
                dr["MBBDeta_Money"] = ValueHandler.GetDecNumberValue(this.nb_SBDeta_Price.Text) * ValueHandler.GetDecNumberValue(this.nb_SBDeta_Count.Text);

                //获取产品类别
                ProductSortOp sortManager = new ProductSortOp();
                ProductSort sortSM = new ProductSort();
                sortSM.PSort_ID = SM.PInfo_PSort_ID;
                sortManager.GetModelById(sortSM);
                dr["PSort_Name"] = sortSM.PSort_Name;
                gv_List.DataSource = dtDetail;
                gv_List.DataBind();
                gv_List.RecordCount = dtDetail.Rows.Count;
                //计算总数量及总金额
                this.nb_MBB_Money.Text = ValueHandler.GetDecNumberValue(dtDetail.Compute("sum(MBBDeta_Money)", "")).ToString();
               
                ClearContent();
            }
        }
        /// <summary>
        /// 结算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bn_Total_Click(object sender, EventArgs e)
        {
            SModel.MBB_Id = this.Id;
            Manager.GetModel(SModel);
            if (SModel.MBB_State == 1)
            {
                ExtAspNet.Alert.Show("该返货单已经结算，不能再次结算！", "操作提示！", MessageBoxIcon.Warning);
            }
            else
            {
                bool blRes = Manager.JS(SModel);
                if (blRes)
                {
                    PageContext.RegisterStartupScript(ExtAspNet.Alert.GetShowInTopReference("结算完成！", "操作提示！", MessageBoxIcon.Information) + ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));
                }
                else
                {
                    ExtAspNet.Alert.Show("结算失败！", "操作提示！", MessageBoxIcon.Error);
                }
            }
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            ClearContent();

        }
        private void ClearContent()
        {
            this.tb_SBDeta_PInfo_Id.Text = "";
            this.hf_SBDeta_PInfo_Id.Text = "";
            this.nb_SBDeta_Count.Text = "1";
            this.nb_SBDeta_Money.Text = "";
            this.nb_SBDeta_Price.Text = "";
            SBDeta_Id = 0;
            this.btnAdd.Text = "添加";
            this.btnAdd.Icon = Icon.Add;
            this.btnCancle.Hidden = true;
        }
        protected void gv_List_RowCommand(object sender, ExtAspNet.GridCommandEventArgs e)
        {
            if (e.CommandName.ToLower() == "delete")
            {
                DataView dv = new DataView(dtDetail);
                SBDeta_Id = ValueHandler.GetIntNumberValue(gv_List.DataKeys[e.RowIndex][0]);
                dv.RowFilter = "MBBDeta_Id=" + SBDeta_Id;
                if (dv.Count > 0)
                {
                    dv[0].Delete();
                }
                dtDetail.AcceptChanges();
                gv_List.DataSource = dtDetail.DefaultView;
                gv_List.DataBind();
                gv_List.RecordCount = dtDetail.Rows.Count;
                //计算总数量及总金额
                this.nb_MBB_Money.Text = ValueHandler.GetDecNumberValue(dtDetail.Compute("sum(MBBDeta_Money)", "")).ToString();

                ClearContent();
            }
            else if (e.CommandName.ToLower() == "edit")
            {
                DataView dv = new DataView(dtDetail);
                SBDeta_Id = ValueHandler.GetIntNumberValue(gv_List.DataKeys[e.RowIndex][0]);
                dv.RowFilter = "MBBDeta_Id=" + SBDeta_Id;
                if (dv.Count > 0)
                {
                    this.tb_SBDeta_PInfo_Id.Text = ValueHandler.GetStringValue(dv[0]["PInfo_Name"]);
                    this.hf_SBDeta_PInfo_Id.Text = ValueHandler.GetStringValue(dv[0]["MBBDeta_PInfo_Id"]);
                    this.nb_SBDeta_Count.Text = ValueHandler.GetIntNumberValue(dv[0]["MBBDeta_Count"]).ToString();
                    this.nb_SBDeta_Money.Text = ValueHandler.GetDecNumberValue(dv[0]["MBBDeta_Money"]).ToString();
                    this.nb_SBDeta_Price.Text = ValueHandler.GetDecNumberValue(dv[0]["MBBDeta_Price"]).ToString();
                    this.btnAdd.Icon = Icon.Accept;
                    this.btnAdd.Text = "确定";
                    this.btnCancle.Hidden = false;
                }
            }
        }

        protected void gv_List_PageIndexChange(object sender, ExtAspNet.GridPageEventArgs e)
        {
            gv_List.PageIndex = e.NewPageIndex;
        }
        /// <summary>
        /// 出库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void bnOutput_Click(object sender, EventArgs e)
        {
            
            SModel.MBB_Id = this.Id;
            DataTable dt = Manager.GetDetail(SModel);
            if (SModel.MBB_Output == 1)
            {
                ExtAspNet.Alert.Show("该返货单已经出库，不能再次出库！", "操作提示！", MessageBoxIcon.Warning);
            }
            //else if (SModel.MBB_PayType == -1)
            //{
            //    ExtAspNet.Alert.Show("该单据结算方式并未保存，请保存后再出库！", "操作提示！", MessageBoxIcon.Warning);
            //    return;
            //}
            //else if (SModel.MBB_AList_Id == 0 || SModel.MBB_AList_Id == -1)
            //{
            //    ExtAspNet.Alert.Show("该单据结算账户并未保存，请保存后再出库！", "操作提示！", MessageBoxIcon.Warning);
            //    return;
            //}


            List<String> LSCheckProduct = Manager.CheckStore(SModel, dt);
            if (LSCheckProduct.Count <= 0)
            {
                bool blRes = Manager.PutOut(SModel,dt);
                if (blRes)
                {
                    ExtAspNet.PageContext.RegisterStartupScript(ExtAspNet.ActiveWindow.GetHidePostBackReference(LinkService.RefreshString));

                }
                else
                {
                    ExtAspNet.Alert.Show("返货单出库失败！", MessageBoxIcon.Error); 
                }
            }
            else //库存不满足
            {
                StringBuilder sbSql = new StringBuilder();
                for (int i = 0; i < LSCheckProduct.Count; i++)
                {
                    if (i == LSCheckProduct.Count - 1)
                        sbSql.Append(LSCheckProduct[i]);
                    else
                        sbSql.Append(LSCheckProduct[i] + ",");
                }
                ExtAspNet.Alert.ShowInTop("产品：" + sbSql.ToString() + "库存不足，无法出库返货单！", MessageBoxIcon.Error);

            }
        }

        #endregion

        #region Method
        private void InitControl()
        {
            bnClose.OnClientClick = ExtAspNet.ActiveWindow.GetHideReference();
            if (Request["Id"] != null)
            {
                Id = ValueHandler.GetIntNumberValue(Request["Id"]);
            }
            bnInput.OnClientClick = win_Confirm.GetShowReference("~/Other/frm_TotalEdit.aspx?Type=3&Id=" + this.Id, "结算方式确认") + ";return false";

            //经办人
            SysUsersOp userManager = new SysUsersOp();
            DataTable dtUser = userManager.GetList("");
            this.ddl_MBB_SUser_Id.DataSource = dtUser;
            this.ddl_MBB_SUser_Id.DataBind();
            this.ddl_MBB_SUser_Id.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            this.ddl_MBB_SUser_Id.SelectedValue = LinkService.GetCurrentUser().SUser_Id.ToString();
            SupplierOp supplierManager = new SupplierOp();
            DataTable dtSupplier = supplierManager.GetList("");
            this.ddl_MBB_Supp_Id.DataSource = dtSupplier;
            this.ddl_MBB_Supp_Id.DataBind();
            this.ddl_MBB_Supp_Id.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            
            //结算方式

            this.ddl_MBB_PayType.DataSource = LinkService.GetPayType();
            this.ddl_MBB_PayType.DataBind();
            this.ddl_MBB_PayType.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            //结算状态
            //this.ddl_SBill_State.DataSource = LinkService.GetSBill_State();
            //this.ddl_SBill_State.DataBind();
            //this.ddl_SBill_State.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            //账户
            AccountListOp AccountManager = new AccountListOp();
            DataTable dtAccountList = AccountManager.GetList("");
            this.ddl_MBB_AList_Id.DataSource = dtAccountList;
            this.ddl_MBB_AList_Id.DataBind();
            this.ddl_MBB_AList_Id.Items.Insert(0, new ExtAspNet.ListItem("-未选择-", "-1"));
            this.dp_MBB_Date.Text = System.DateTime.Now.ToString("yyyy-MM-dd");


        }
        private void GetAndBind()
        {
            SModel.MBB_Id = Id;
            dtDetail = Manager.GetDetail(SModel);

            gv_List.DataSource = dtDetail;
            gv_List.DataBind();
            gv_List.RecordCount = dtDetail.Rows.Count;
            if (Id != 0)
            {
                this.tb_MBB_Code.Text = SModel.MBB_Code;
                
                this.tb_MBB_Reason.Text = SModel.MBB_Reason;
                this.ddl_MBB_AList_Id.SelectedValue = SModel.MBB_AList_Id.ToString();
                this.ddl_MBB_PayType.SelectedValue = SModel.MBB_PayType.ToString(); 
                this.ddl_MBB_SUser_Id.SelectedValue = SModel.MBB_SUser_Id.ToString();
                this.ddl_MBB_Supp_Id.SelectedValue = SModel.MBB_Supp_Id.ToString();

                this.dp_MBB_Date.Text = SModel.MBB_Date.ToString("yyyy-MM-dd");
                this.nb_MBB_Money.Text = SModel.MBB_Money.ToString();  
                
                //未出库
                if (SModel.MBB_Output == 0)
                {
                    bnSave.Enabled = true;
                    bnInput.Enabled = false;
                    bnOutput.Enabled = true;
                    lb_MBB_Output.Text = "<span style='color:Red;font-weight:bold;'>未出库</span>";
                }
                else//已出库
                {
                    bnSave.Enabled = false;
                    bnInput.Enabled = true;
                    bnOutput.Enabled = false;
                    btnAdd.Enabled = false;
                    SimpleForm2.Hidden = true;
                    gv_List.Columns[6].Hidden = true;
                    gv_List.Columns[7].Hidden = true;
                    lb_MBB_Output.Text = "<span style='color:Green;font-weight:bold;'>已出库</span>";

                }
                if (SModel.MBB_State == 1)
                {
                    bnSave.Enabled = false;
                    bnInput.Enabled = false;
                    bnOutput.Enabled = false;
                    btnAdd.Enabled = false;
                    SimpleForm2.Hidden = true;
                    gv_List.Columns[6].Hidden = true;
                    gv_List.Columns[7].Hidden = true;
                    this.lb_MBB_State.Text = "<span style='color:Green;font-weight:bold;'>已结算</span>";
                }
                else
                    this.lb_MBB_State.Text = "<span style='color:Red;font-weight:bold;'>未结算</span>";


            }
            else
            {
                this.tb_MBB_Code.Text = Coder.CreateCoder(EMenuList.返货管理);
                this.bnInput.Enabled = false;
                bnOutput.Enabled = false;
                lb_MBB_Output.Text = "<span style='color:Red;font-weight:bold;'>未出库</span>";
                this.lb_MBB_State.Text = "<span style='color:Red;font-weight:bold;'>未结算</span>";                
            } 
            this.bnInput.ToolTip = "只有入库状态下才可结算！";
            this.bnSave.ToolTip = "只有未入库的才可保存！";
            this.bnOutput.ToolTip = "只有未出库状态下才可出库！";
        }

        #endregion

        #region Property
        MyBackBillOp Manager = new MyBackBillOp();
        new Sale_Model.MyBackBill SModel = new Sale_Model.MyBackBill();
        public DataTable dtDetail
        {
            get
            {
                return ViewState["dtDetail"] as DataTable;
            }
            set
            {
                ViewState["dtDetail"] = value;
            }
        }
        /// <summary>
        /// 子表当前编辑的关键子
        /// </summary>
        public int SBDeta_Id
        {
            get
            {
                return ValueHandler.GetIntNumberValue(ViewState["SBDeta_Id"]);
            }
            set
            {
                ViewState["SBDeta_Id"] = value;
            }
        }
        #endregion
    }
}
